import Foundation
import Combine

class UserProfile: ObservableObject {
    @Published var name: String = "张三"
    @Published var weight: Double = 70.0 // 默认值，单位：公斤
    @Published var goal: Double = 2000.0 // 默认目标，单位：毫升
    
    init() {
        // 从UserDefaults加载数据，如果没有则使用默认值
        loadFromUserDefaults()
    }
    
    // 根据体重计算推荐饮水量
    func calculateRecommendedGoal() -> Double {
        // 简单计算：每公斤体重约需30毫升水
        return weight * 30
    }
    
    // 更新用户信息并计算新的推荐目标
    func updateProfile(name: String, weight: Double) {
        self.name = name
        self.weight = weight
        self.goal = calculateRecommendedGoal()
    }
    
    // 从UserDefaults加载数据
    private func loadFromUserDefaults() {
        let defaults = UserDefaults.standard
        
        if let savedName = defaults.string(forKey: "userName"), !savedName.isEmpty {
            name = savedName
        }
        
        let savedWeight = defaults.double(forKey: "userWeight")
        if savedWeight > 0 {
            weight = savedWeight
        }
        
        let savedGoal = defaults.double(forKey: "userGoal")
        if savedGoal > 0 {
            goal = savedGoal
        } else {
            // 如果没有保存的目标，使用计算的推荐值
            goal = calculateRecommendedGoal()
        }
    }
}
